<template>
	<div class="smsManage" :style="[{'zoom': zoom}]">
		<div class="smsManageStatistics">
      <div class="chartPie">
        <div class="chartPieTitle"><img style="margin-right: 5px" src="../../img/images/sms-title.png"/> 短信信息汇总</div>
        <div class="chartContent">
          <div class="messageCountChart" id="messageCountChart"></div>
          <div class="messageSummary">
            <el-row :grid="20">
              <el-col :span="8">
                  <div class="count">{{summaryData.total}}</div>
                  <div class="describe">短信总额(条)</div>
              </el-col>
              <el-col :span="8">
                <div class="count">{{summaryData.used}}</div>
                <div class="describe">使用数量(条)</div>
              </el-col>
              <el-col :span="8">
                <div class="count-able">{{summaryData.enable}}</div>
                <div class="describe">可用数量(条)</div>
              </el-col>
            </el-row>
            <el-row >
              <el-col :span="8" class="operateBtn">
                <el-button type="primary" @click="handleOperate('1')">调整</el-button>
              </el-col>
              <el-col :span="8"  class="operateBtn">
                <el-button type="primary" @click="handleOperate('2')">调整</el-button>
              </el-col>
              <el-col :span="8"  class="operateBtn">
                <el-button type="info" @click="handleViewRecord">操作记录</el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
      <el-divider direction="vertical"></el-divider>
      <div class="chartLine">
        <div class="chartLineTitle">短信使用趋势图</div>
        <div class="messageMonthChart" id="messageMonthChart"></div>
      </div>
		</div>
		<div class="list-search" style="margin-left: 25px">
        <div class="singe-search" style="margin-right: 70px">
          <el-date-picker ref="daterange" v-model="queryForm.daterange" type="daterange" range-separator="-"
                          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </div>
        <div class="singe-search" >
          <el-cascader style="width: 296px;" v-model="queryForm.deptIds" :options="deptTree" clearable="true" :props="defaultProps"
                       placeholder="使用部门">
          </el-cascader>
        </div>
        <div class="singe-search">
          <el-input v-model="queryForm.senderName" placeholder="请输入使用人"></el-input>
        </div>
        <div  class="singe-search">
          <el-select style="width: 296px;" v-model="queryForm.status" placeholder="是否生效">
            <el-option :key="0" :label="'否'" :value="0"></el-option>
            <el-option :key="1" :label="'是'" :value="1"></el-option>
          </el-select>
        </div>
        <div class="singe-search">
          <el-button class="singe-search-btn1" type="primary" @click="handleQuery">查询</el-button>
          <el-button class="singe-search-btn2" type="info" @click="handleReset">重置</el-button>
        </div>
		</div>
		<div class="table-main">
			<el-table :data="tableData" style="width: 100%" :height="tableHeight">
				<el-table-column type="index" label="序号" width="70" align="center">
				</el-table-column>
				<el-table-column prop="deptName" label="使用部门" min-width="120">
				</el-table-column>
				<el-table-column prop="sender" label="发送人" min-width="120">
				</el-table-column>
				<el-table-column prop="receiverPhone" label="接受手机号" min-width="120">
				</el-table-column>
				<el-table-column prop="createTime" label="发送时间" min-width="120">
				</el-table-column>
				<el-table-column prop="content" label="短信内容" min-width="120">
				</el-table-column>
				<el-table-column  label="是否生效" min-width="120">
          <template slot-scope="{row}">
            {{row.status==1?'是':'否'}}
          </template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryForm.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="queryForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="queryForm.total">
			</el-pagination>
		</div>
    <el-dialog :title="'调整数量:'" :visible.sync="operateDialogVisible" width="782px" class="form-dialog" append-to-body>
      <el-form :model="operateForm"  ref="form" label-width="100px" label-position="top" :rules="rules">
        <el-form-item :label="'调整数量'"  prop="operateCount">
          <el-input props="operateCount" v-model="operateForm.operateCount" :placeholder="'请输入数量（调整）'"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
					<el-button @click="handleSubmitCancel" size="small">
						取 消
					</el-button>
					<el-button type="primary" @click="handleSubmit" size="small" style="background-color:#2E488B">
						提 交
					</el-button>
				</span>
    </el-dialog>

    <el-dialog title="操作记录" :visible.sync="recordDialogVisible" width="782px" class="form-dialog" append-to-body>
      <el-table :data="recordTableData" style="width: 100%" :height="tableHeight" stripe="true" border="true">
        <el-table-column prop="createUserName" label="操作人" min-width="120">
        </el-table-column>
        <el-table-column  label="操作功能" min-width="120">
          <template slot-scope="{row}">
            {{getOperateType(row.type)}}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="操作内容" min-width="120">
        </el-table-column>
        <el-table-column prop="status" label="操作状态" min-width="120">
          <template slot-scope="{row}">
            {{row.status=='1'?'成功':'失败'}}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" min-width="120">
        </el-table-column>
      </el-table>
    </el-dialog>
	</div>
</template>

<script>
	import {
		dateFormat
	} from '../../util/date.js';
  import {getDeptTreeAuth} from "@/api/system/dept";

  import {
    getSmsConfigDetail,
    updateSmsConfig
  } from "@/api/sms/smsconfig";

  import {
    getSmsConfigChangeLogPage,
  } from "@/api/sms/smsconfigchangelog";
  import {
    getSmsRecordsPage,
    getDataByMonth
  } from "@/api/sms/smsrecords";

  import {} from "@/api/sms/smstemplate";

	export default {
		name: 'smsManage',
    components: {},
    data() {
			return {
        width: 1848,
        zoom: 1,
				radio: 3,
				daterange: [],
				tableData: [],
        deptTree: [],
        defaultProps: {
          children: 'children',
          label: 'title',
          value: 'id',
          checkStrictly: true
        },
        summaryData:{
          total:0,
          used:0,
          enable:0,
        },
        queryForm: {
          pageNo:1,
          pageSize:20,
          total:0,
          deptId:'',
          deptIds:[],
          senderName:'',
          daterange:'',
          status:'',
          startDate:'',
          endDate:'',
        },
        createDept:[],
        operateDialogVisible:false,
        recordDialogVisible:false,
        operateForm: {id:'123456',
          operateType:'',
          operateCount:null
        },
        recordTableData:[

        ],
        rules:{
          operateCount: [
            {
            required: true,
            message: '请填写数量',
            trigger: 'blur'
            },
            {validator: this.validateOperateCount, trigger: 'blur'}
          ],
        },
        dateList:[],
        dateDataList:[],

			}
		},
		computed: {
			tableHeight() {
				let h = document.body.clientHeight - 294-202;
				return h;
			},
		},
    created(){
      this.getList()
      this.getDeptTree()
      this.getSmsConfig()
    },
		mounted() {
      // this.initPieChart()
      let self = this;
      window.addEventListener('resize', () => {
        self.getZoom();
      });
      this.getZoom();
      this.loadLineChartData()

		},
		methods: {
      validateOperateCount(rule, value, callback){
        const positiveIntegerPattern = /^[1-9]\d*$/;

        // 使用正则表达式的 test 方法检查输入是否符合规则
        if(positiveIntegerPattern.test(value)){
          if(value<0){
            callback(new Error('调整数量不可以为负数'));
          }else{
            if(this.operateForm.operateType=='1'){
              if(value<this.summaryData.used){
                callback(new Error('短信总数不可以小于已使用的数量'));
              }else{
                callback();
              }
            }else{
              if(value>this.summaryData.total){
                callback(new Error('已使用数量不可以大于短信总数'));
              }else{
                callback();
              }
            }
          }
        }else{
          this.operateForm.operateCount=0
          callback(new Error('请输入正确的数字'));
        }
      },
      getZoom() {
        let self = this;
        let w = document.body.clientWidth;
        if (w < self.width) {
          self.zoom = (w / self.width) - 0.1;
        } else {
          self.zoom = 1;
        }
      },
      getOperateType(value){
        let label='--'
        if(value=='1'){
          label= '总数调整'
        }else if(value=='2'){
          label= '已使用调整'
        }
        return label
      },
      handleSubmit(){
        let form={
          id:this.operateForm.id,
          type:this.operateForm.operateType,
          count:this.operateForm.operateCount,
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            updateSmsConfig(form).then(res=>{
              let code=res.data.code
              if(code=='200'){
                this.operateDialogVisible=false
                this.$message.success("调整成功")
                this.getSmsConfig()
              }else{
                this.$message.error("调整失败")
                this.getSmsConfig()
              }
            })
          }
        })
      },
      handleSubmitCancel(){
        this.operateDialogVisible=false
        this.operateForm.operateType='',
        this.operateForm.operateCount=''
      },
      resetForm() {
        this.queryForm = {
          pageNo:1,
          pageSize:20,
          total:0,
          deptId:'',
          senderName:'',
          daterange:'',
          status:'',
          startDate:'',
          endDate:'',
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.getList()
      },
      getList(){
        if(this.queryForm.deptIds&&this.queryForm.deptIds.length>0){
          this.queryForm.deptId=this.queryForm.deptIds[this.queryForm.deptIds.length-1]
        }else{
          this.queryForm.deptId=''
        }
        getSmsRecordsPage(this.queryForm.pageNo, this.queryForm.pageSize, this.queryForm).then(res=>{
          console.log('getSmsRecordsPage----------',res)
          let data=res.data.data
          this.tableData=data.records
          this.tableData=data.records
          this.queryForm.pageNo=data.current
          this.queryForm.pageSize=data.size
          this.queryForm.total=data.total
        })
      },
      getSmsConfig(){
        getSmsConfigDetail('123456').then(res=>{
          console.log('getSmsConfigDetail----------',res)
          if(res.data.code==200){
            this.summaryData=res.data.data
            this.initPieChart()
          }
        })
      },
      /**
       * 查询
       */
      handleQuery(){
        this.getList()
      },
      /**
       * 重置
       */
      handleReset(){
       this.resetForm()
      },
      /**
       * 获取部门树
       */
      getDeptTree() {
        let that = this;
        getDeptTreeAuth().then(res => {
          console.log('部门树', res.data);
          if (res.data.code === 200) {
            that.deptTree = res.data.data;
          }
        })
      },
      /**
       * 初始化饼图
       */
			initPieChart(){
        let pieDom = this.$echarts.init( document.getElementById('messageCountChart'));
        let pieOption = {
          tooltip: {
            trigger: 'item'
          },
          grid:{
            left:'1'
          },
          legend: {
            top: '45%',
            orient: 'vertical',
            left: '43%',
            align:'left',
          },
          series: [
            {
              name: '短信汇总',
              type: 'pie',
              radius: ['30%', '60%'],
              avoidLabelOverlap: false,
              center: ['22%', '60%'],
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: false,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: this.summaryData.enable, name: '可用数量' },
                { value: this.summaryData.used, name: '使用数量' },
              ]
            }
          ]
        };
        pieDom.setOption(pieOption);
      },
      /**
       * 获取折线图数据
       */
      loadLineChartData(){
        getDataByMonth().then(res=>{
          let data=res.data.data
          data.forEach(item=>{
            this.dateList.push(item.sendMonth);
            this.dateDataList.push(item.sendCount);
          })
          this.initLineChart()
        })
      },
      initLineChart(){
        let lineDom = this.$echarts.init( document.getElementById('messageMonthChart'));
        let lineOption = {
          xAxis: {
            type: 'category',
            data: this.dateList
          },
          yAxis: {
            type: 'value'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              animation: false,
              label: {
                backgroundColor: '#505765'
              }
            }
          },
          series: [
            {
              data: this.dateDataList,
              type: 'line'
            }
          ],
          grid: {
            top: '10%', // 可以根据需要调整 top、bottom、left、right 的值
            bottom: '10%',
            left: '10%',
            right: '10%',
            height: '60%' // 调整这个值来改变图表的高度
          }
        };
        lineDom.setOption(lineOption);
      },
      handleOperate(val){
        this.operateDialogVisible=true;
        this.operateForm.operateType=val;
        this.operateForm.operateCount='';
      },
      handleViewRecord(){
        this.recordDialogVisible=true
        this.loadOperateRecordList()
      },
      loadOperateRecordList(){
        getSmsConfigChangeLogPage().then(res=>{
          if(res.data.code==200){
            let data=res.data.data
            this.recordTableData=data.records
          }
        })
      }
		}
	}
</script>

<style lang="scss" >
	@import '../../styles/page/list';

	.smsManage {
		width: 100%;
		height: 100%;
    overflow: hidden;
    .list-search{
      .el-input__inner{
        height: 36px;
        line-height: 36px;
        margin-top: 5px;
      }
      .singe-search{
        .el-input .el-input__inner {
          height: 36px;
          line-height: 36px;
        }
        .singe-search-btn1{
          width: 88px !important;
          height: 36px !important;
          background: #2E488B !important;
          -webkit-box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
          box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
          border-radius: 4px 4px 4px 4px !important;
          opacity: 1 !important;
          padding: 0 !important;
          font-size: 14px !important;
          font-family: PingFang SC-Regular, PingFang SC !important;
          font-weight: 400 !important;
          color: #FFFFFF !important;
        }
        .singe-search-btn2{
          width: 88px !important;
          height: 36px !important;
          background: #FFFFFF !important;
          -webkit-box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
          box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
          border-radius: 4px 4px 4px 4px !important;
          opacity: 1 !important;
          border: 1px solid #C1D3EE !important;
          padding: 0 !important;
          font-size: 14px !important;
          font-family: PingFang SC-Regular, PingFang SC !important;
          font-weight: 400 !important;
          color: #2E488B !important;
        }
      }
    }
    .form-dialog {
      border-radius:10px;
      .Bag-ul {
        li {
          display: inline-block;
          list-style: none;
          font-size: 15px;
          width: 50%;
          height: 35px;
          line-height: 35px;
        }
      }
      .el-dialog .el-dialog__header {
        text-align: left;
      }
    }
		.smsManageStatistics {
			width: auto;
			height: 202px;
			display: flex;
			flex-wrap: wrap;
			align-items: center;
      background-color: #FFFFFF;
      border-radius: 4px;
      margin: 25px 0 0 25px;
      box-shadow: 0px 6px 40px 5px rgba(0, 0, 0, 0.06), 0px 6px 8px 0px rgba(0, 0, 0, 0.05);
      .chartPie{
        border-radius: 4px;
        height: 202px;
        width: 50%;
        //background-color: #00a680;
        .chartContent{
          display: flex;
          .messageCountChart{
            height: 172px;
            width: 300px;
            margin: -20px 0 0 20px;
          }
          .messageSummary{
            padding-top: 40px;
            width: calc(100% - 250px);
            .operateBtn{
              display: flex;
              justify-content: center;
            }
            .count{
              display: flex;
              justify-content: center;
              font-size: 22px;
              padding: 2px 10px;
              font-weight: 650;
            }
            .count-able{
              display: flex;
              justify-content: center;
              font-size: 22px;
              padding: 2px 10px;
              color:#3679DE;
              font-weight: 650;
            }
            .describe{
              display: flex;
              justify-content: center;
              padding: 2px 10px;
              font-size: 14px
            }
            .el-button--primary{
              // background: #FFFFFF;
              box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.05);
              border-radius: 4px;
              font-size: 13px;
              // background: linear-gradient(90deg, #97C0FF 0%, #3A92F9 100%);
              background-color: #2E488B;
              border: 1px solid #eff4ff;
              height: 26px;
              line-height: 1px;
            }

            // 白色按钮样式
            .el-button--info{
              // background: #FFFFFF;
              box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.05);
              border-radius: 4px;
              font-size: 13px;
              // background: linear-gradient(90deg, #97C0FF 0%, #3A92F9 100%);
              background-color: #ffffff;
              border: 1px solid #2E488B;
              color: #2E488B;
              height: 26px;
              line-height: 1px;
            }
          }
        }
        .chartPieTitle{
          padding: 13px 0 0 36px;
          font-weight: 600;
          color: #2E488B ;
          font-size: 16px;
          display: flex;
        }

      }
      .chartLine{
        border-radius: 4px;
        height: 202px;
        width: auto;
        .chartLineTitle{
          padding: 13px 0 0 36px;
          font-weight: 600;
          font-size: 14px;
        }
        .messageMonthChart{
          height: 170px;
          width: 800px;
        }
      }
      .el-divider--vertical {
        display: inline-block;
        width: 1px;
        height: 6em;
        margin: 0;
        vertical-align: middle;
        position: relative;
      }
		}


		.table-main {
			margin-left: 25px;
		}
	}
</style>
